import numpy as np
# from collections import OrderedDict, Counter
# import pandas as pd

# from processing.utils import div, reduce_sum

# import requests
# import json
# import re
# import pandas as pd
# import time

import time
import json
import hashlib
import requests

import re
class gptApiNonStream:

    def __init__(self, prompt):
        self.prompt = prompt
        self.time_stamp = str(int(time.time() * 1000))
        self.model_name = "gpt-3.5-turbo"  # gpt-4-1106-preview | gpt-3.5-turbo
        self.openai = self.init_gpt(self.prompt)
        self.load_config()

    
    def load_config(self):
        self.puid = 22330313
        # print('ssssssss', self.puid)
        self.fid = 1385
        self.token = 'cXing1993'
        self.url = 'https://gpt.chaoxing.com/openai/v1/chat/AIReply'
        self.map_data = {
            "puid": self.puid,
            "fid": self.fid,
            "openai": self.openai,
            "_time": self.time_stamp,
            "token": self.token
        }
        self.inf_enc = self.inf_enc_generator(self.map_data, self.token)

    def get_gpt_res(self):
        data = {
            "openai": self.openai,
            "puid": self.puid,
            "fid": self.fid,
            "_time": self.time_stamp,
            "token": self.token,
            "inf_enc": self.inf_enc
        }
        try:
            response = requests.post(self.url, data=data)
            response.raise_for_status()
            # 流式输出
            response.encoding = 'utf-8'  # 设置响应的编码方式为 UTF-8

            return response.text
        except requests.exceptions.RequestException as e:
            raise SystemExit(e)

    def init_gpt(self, prompt:str, model_name="gpt-3.5-turbo"):
        try:
            json_con = {
                "role": "user",
                "content": prompt
            }
            messages = [json_con]
            json_data = {
                "model": model_name,
                "messages": messages,
                "temperature": 0.9,
            }
            return json.dumps(json_data)
        except Exception as e:
            return str(e)

    def inf_enc_generator(self, fields, token):
        names = sorted(fields.keys())
        builder = "&".join([f"{name}={fields[name]}" for name in names])

        if token == "****":
            builder += "&_key=********&X"  # pc, 张建勇
        elif token == "cXing1993":
            builder += "&_key=S6njM)ypY@CO&X"  # 通用接口，我这边定义的
        else:
            builder += "&_key=*****XS"  # 手机端的

        try:
            return self.md5(builder)
        except Exception as e:
            raise SystemExit(e)

    def md5(self, input_string):
        md5_hash = hashlib.md5()
        md5_hash.update(input_string.encode('utf-8'))
        return md5_hash.hexdigest()

def get_gpt_ans(prompt):
    my_chat = gptApiNonStream(prompt)
    res_chart = my_chat.get_gpt_res()
    res_chart_dict = json.loads(res_chart)
    output = res_chart_dict['choices'][0]['message']['content']
    return output


